import i18n from '@/i18n'
import Vue from 'vue'

let vueI18n = new Vue({
  i18n
})

const dept = {
  state: {
    checkRules: {
      name: [
        { required: true, message: vueI18n.$t('message.validate.devices.dept.name'), trigger: 'blur' }
      ]
    },

    customOption: [],
    deptTree: [],
    deptTreeAll: []
  },
  mutations: {
    setCustomOption (state, data) {
      state.customOption = data
    },
    setdeptTree (state, data) {
      state.deptTree = data
    },
    setdeptTreeAll (state, data) {
      state.deptTreeAll = data
    }
  },
  actions: {
    async getDeptOption (context) {
      let response = await context.dispatch('axios', {
        method: 'get',
        url: '/api/abs/devices/depts/',
        params: {
          center: 0
        }
      })
      context.commit('setCustomOption', response.data)
    },
    async getDeptTree (context) {
      let response = await context.dispatch('axios', {
        method: 'get',
        url: '/api/abs/devices/dept_tree/',
        params: {
          center: 0
        }
      })
      context.commit('setdeptTree', [response.data])
    },
    async getDeptTreeAll (context) {
      let response = await context.dispatch('axios', {
        method: 'get',
        url: '/api/abs/devices/dept_tree/'
      })
      context.commit('setdeptTreeAll', [response.data])
    }
  },
  getters: {
    customOption (state) {
      return state.customOption.map(item => {
        return {
          key: item.id,
          value: item.id,
          label: item.name
        }
      })
    },
    deptTreeForSelectCu (state) {
      return recursiveDeptTree(state.deptTreeAll)
    }
  }
}

function recursiveDeptTree (data) {
  return [...data.map(item => {
    if (item.node_type === 'root') {
      return {
        ...item,
        children: recursiveDeptTree(item.children),
        node_key: 'root'
      }
    }
    // 当节点为全网或部门时
    if (item.node_type === 'dept') {
      return {
        ...item,
        children: recursiveDeptTree(item.children)
      }
    }
    // 当节点为地球站时
    if (item.node_type === 'station') {
      // 当地球站中只有一个终端时,将cu的信息直接显示到name中
      if (item.cus.length === 1) {
        return {
          ...item,
          node_key: `cu_${item.cus[0].id}`,
          name: `${item.name}(${item.cus[0].device})`
        }
      } else if (item.cus.length > 1) {
        // 当地球站中有多个终端时
        return {
          ...item,
          children: item.cus.map(cuItem => {
            return {
              ...cuItem,
              name: cuItem.device,
              node_key: `cu_${cuItem.id}`
            }
          })
        }
      } else {
        // 若该地球站中没有终端,直接返回源数据
        return {
          ...item
        }
      }
    }
  })]
}

export default dept
